<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\work;

use think\facade\Db;
use think\exception\ValidateException;
use app\common\dao\work\WorkExpendApplyDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\approval\ApprovalLogRepository;
use app\common\repositories\approval\ApprovalFlowRepository;
use app\common\repositories\approval\ApprovalConfigRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;
use app\common\repositories\approval\ApprovalReceivesRepository;

/**
 * Class WorkExpendApplyRepository
 * @package app\common\repositories\work
 * @mixin WorkExpendApplyDao
 */
class WorkExpendApplyRepository extends BaseRepository
{
    public function __construct(WorkExpendApplyDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, $propertyId)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->order('id', 'desc')
            ->select();
        /** @var ApprovalConfigRepository $configRepository */
        $configRepository = app()->make(ApprovalConfigRepository::class);
        $flowTypeData = $configRepository::FLOW_TYPE_B;
        foreach ($list as $k => $v) {
            $list[$k]['report_type'] = ($flowTypeData[$v['report_type']] ?? '');
        }
        return compact('count', 'list');
    }

    public function addInfo(array $data, int $propertyId = 1, int $userId = 0)
    {
        /** @var ApprovalConfigRepository $configRepository */
        $configRepository = app()->make(ApprovalConfigRepository::class);
        $configInfo = $configRepository->get($data['config_id']);
        if (!$configInfo) {
            throw new ValidateException('非法操作');
        }
        return Db::transaction(function () use ($configInfo, $data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $data['picture'] = implode(',', (array)$data['picture']);
            $data['report_type'] = $configInfo['flow_type']; ##  流程类型
            $resInfo = $this->dao->create($data);
            $acceptUidData = $configInfo['accept_uids'] ?? [];
            $copyUidData = $configInfo['copy_uids'] ?? [];
            if (!is_array($configInfo['accept_uids'])) {
                $acceptUidData = array_filter(explode(',', $configInfo['accept_uids']));
            }
            if (!is_array($configInfo['copy_uids'])) {
                $copyUidData = array_filter(explode(',', $configInfo['copy_uids']));
            }

            ## 添加流程记录
            /** @var ApprovalFlowRepository $approvalFlowRepository */
            $approvalFlowRepository = app()->make(ApprovalFlowRepository::class);
            $flowData['submit_uid'] = $userId;  ##  提交人 ID
            $flowData['source_id'] = $resInfo['id'];  ##  流程源 ID
            $flowData['is_type'] = $configInfo['is_type']; ##  流程类型
            $flowData['flow_type'] = $configInfo['flow_type']; ##  流程类型
            $flowData['audit_type'] = $configInfo['audit_type']; ##  审核方式
            $flowData['present_uid'] = $acceptUidData[0]; ##  第一个审核人
            $flowInfo = $approvalFlowRepository->addInfo($flowData, $propertyId, $userId);

            ## 添加流程日志
            /** @var ApprovalLogRepository $approvalLogRepository */
            $approvalLogRepository = app()->make(ApprovalLogRepository::class);
            $logData['user_id'] = $userId;
            $logData['flow_id'] = $flowInfo['id'];
            $logData['remark'] = '创建申请';
            $approvalLogRepository->addInfo($logData, $propertyId, $userId);

            ## 添加流程数据
            if ($acceptUidData || $copyUidData) {
                /** @var ApprovalReceivesRepository $approvalReceivesRepository */
                $approvalReceivesRepository = app()->make(ApprovalReceivesRepository::class);
                $approvalReceivesRepository->batchAdd($propertyId, $flowInfo, $acceptUidData, 1, 1);## 提交 需确认审核
                $approvalReceivesRepository->batchAdd($propertyId, $flowInfo, $copyUidData, 3, 7); ## 抄送 无需审批
            }

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'WROK.EXPEND_APPLY.ADD', $data);
            return $resInfo;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'WROK.EXPEND_APPLY.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }

    public function getDetail(int $id)
    {
        return $this->dao->getSearch(['id' => $id])
            ->find();
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {

        return Db::transaction(function () use ($info, $userId) {

            ## 删除流程表
            /** @var ApprovalFlowRepository $approvalFlowRepository */
            $approvalFlowRepository = app()->make(ApprovalFlowRepository::class);

            ## 删除流程日志
            /** @var ApprovalLogRepository $approvalLogRepository */
            $approvalLogRepository = app()->make(ApprovalLogRepository::class);

            ## 删除流程列表
            /** @var ApprovalReceivesRepository $approvalReceivesRepository */
            $approvalReceivesRepository = app()->make(ApprovalReceivesRepository::class);
            $flowInfo = $approvalFlowRepository->getSearch([])
                ->where('flow_type', 'expend_apply')
                ->where('source_id', $info['id'])
                ->find();

            if ($flowInfo) {
                $approvalLogRepository->deleteByFlowId($flowInfo['id']);
                $approvalReceivesRepository->deleteByFlowId($flowInfo['id']);
                $flowInfo->delete();
            }

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'WROK.EXPEND_APPLY.DEL', $info);
            $this->dao->delete($info['id']);
        });
    }

}